package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	// 引入数据库
	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	Id       int
	Username string
	Password string
}

var db orm.Ormer

func init() {
	// 开启调试模式
	orm.Debug = true
	// 注册驱动
	orm.RegisterDriver("mysql",orm.DRMySQL)
	// 获取数据库连接
	orm.RegisterDataBase("default","mysql","root:root@tcp(127.0.0.1:3306)/demo?charset=utf8",30)
	// 将model进行注册
	orm.RegisterModel(new(User))
	db = orm.NewOrm()
	fmt.Println("init success")
}

func AddUser(u User) error {
	_, err := db.Insert(&u)
	return err
}

func GetUser(u User) (user User, err error) {
	err = db.Read(&u)
	return u,err
}

func GetAllUsers() ([]User,error) {
	var users []User
	seter := db.QueryTable(new(User))
	all, err := seter.All(&users)
	fmt.Println("查询出来的数量 = "+strconv.Itoa(int(all)))
	return users,err
}

func UpdateUser(u User)  error {
	_, err := db.Update(&u)
	return err
}

func DeleteUser(id int) error {
	_, err := db.Delete(&User{Id: id})
	return err
}
